package com.github.baichuan.iot.gateway.handler;

import com.github.baichuan.iot.gateway.context.DeviceContext;
import com.github.baichuan.iot.gateway.context.DeviceContextCache;
import com.github.baichuan.iot.protocol.codec.MessageDecodeContext;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.lang.ref.WeakReference;

/**
 * 设备上下文缓存处理器
 */
@Slf4j
@ChannelHandler.Sharable
public class DeviceContextHandler extends ChannelInboundHandlerAdapter {
    private DeviceContextCache cache;

    public DeviceContextHandler(@NonNull DeviceContextCache cache){
        this.cache = cache;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageDecodeContext inbound = (MessageDecodeContext) msg;
        String device = inbound.getDevice();
        boolean online = !cache.contains(device);
        DeviceContext context = cache.get(device);

//        inbound.setDebug(context.isDebug());
        inbound.getAttributes().putAll(context.getAttributes());
//        context.setLastInbound(inbound);

        //更新终端上下文信息
        Channel channel = ctx.channel();
        context.setChannel(new WeakReference<>(channel));
        context.setRecipient(channel.remoteAddress());

//        //将终端上下文信息写入报文上下文
//        if(context.getAttributes() != null){
//            inbound.getAttributes().putAll(context.getAttributes());
//        }

        if (online) {
            if(context.isDebug()){
                log.info("[DEBUG:{}] Tbox is online", device);
            }
            else{
                log.debug("TBox {} is online", device);
            }
            cache.online(context);
        }

        ctx.fireChannelRead(msg);
    }
}
